const express = require('express');
const { authenticateToken, requirePermissions } = require('../middleware/auth');
const Order = require('../models/Order');

const router = express.Router();

// 所有订单路由都需要认证
router.use(authenticateToken);

/**
 * 获取订单列表
 * GET /api/orders
 */
router.get('/', requirePermissions(['order:view']), async (req, res) => {
  try {
    const {
      page = 1,
      pageSize = 10,
      search = '',
      status = null,
      start_date = null,
      end_date = null,
      sort = 'created_at',
      order = 'DESC'
    } = req.query;

    const result = await Order.getList({
      page: parseInt(page),
      pageSize: parseInt(pageSize),
      search,
      status,
      start_date,
      end_date,
      sort,
      order
    });

    res.paginate(result.orders, result.total, page, pageSize);

  } catch (error) {
    console.error('获取订单列表失败:', error);
    res.error('获取订单列表失败', 500, error.message);
  }
});

/**
 * 获取订单详情
 * GET /api/orders/:id
 */
router.get('/:id', requirePermissions(['order:view']), async (req, res) => {
  try {
    const { id } = req.params;
    
    const order = await Order.findById(id);
    if (!order) {
      return res.error('订单不存在', 404);
    }

    res.success(order);

  } catch (error) {
    console.error('获取订单详情失败:', error);
    res.error('获取订单详情失败', 500, error.message);
  }
});

/**
 * 更新订单状态
 * PUT /api/orders/:id/status
 */
router.put('/:id/status', requirePermissions(['order:edit']), async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;

    if (!status) {
      return res.error('订单状态不能为空', 400);
    }

    // 验证状态值
    const validStatuses = ['pending_payment', 'processing', 'shipped', 'completed', 'cancelled', 'refunded'];
    if (!validStatuses.includes(status)) {
      return res.error('无效的订单状态', 400);
    }

    const order = await Order.findById(id);
    if (!order) {
      return res.error('订单不存在', 404);
    }

    const updatedOrder = await Order.updateStatus(id, status);
    res.success(updatedOrder, '订单状态更新成功');

  } catch (error) {
    console.error('更新订单状态失败:', error);
    res.error('更新订单状态失败', 500, error.message);
  }
});

/**
 * 获取待处理订单统计
 * GET /api/orders/stats/pending
 */
router.get('/stats/pending', requirePermissions(['order:view']), async (req, res) => {
  try {
    const stats = await Order.getPendingStats();
    res.success(stats);

  } catch (error) {
    console.error('获取待处理订单统计失败:', error);
    res.error('获取待处理订单统计失败', 500, error.message);
  }
});

module.exports = router;
